package com.nl.lib_core.view.selector

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import com.nl.lib_core.R

/**
 * 作者: wangfei 创建时间: 2021/9/1 包名: com.nl.lib_core.view 类名: LoadingInitView
 * 选择按钮的模板模式布局根据不同的布局方式去创建,配合其管理容器[selectorGroup]进行使用
 */
abstract class Selector : FrameLayout, View.OnClickListener {
  var selectorTag: String? = null

  var groupTag: String? = null
    private set

  private var selectorGroup: SelectorGroup? = null

  constructor(context: Context) : super(context) {
    initView(context, null)
  }

  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
    initView(context, attrs)
  }

  constructor(
      context: Context,
      attrs: AttributeSet?,
      defStyleAttr: Int
  ) : super(context, attrs, defStyleAttr) {
    initView(context, attrs)
  }

  private fun initView(context: Context, attrs: AttributeSet?) {
    if (attrs != null) {
      val typedArray = context.obtainStyledAttributes(attrs, R.styleable.Selector)
      val tagResId = typedArray.getResourceId(R.styleable.Selector_tag, 0)
      selectorTag = context.getString(tagResId)
      onObtainAttrs(typedArray)
      typedArray.recycle()
    } else {
      selectorTag = "default tag"
    }
    val view = onCreateView()
    val params =
        LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    this.addView(view, params)
    setOnClickListener(this)
  }

  private fun onObtainAttrs(typedArray: TypedArray?) {}

  fun setGroup(groupTag: String?, selectorGroup: SelectorGroup?): Selector {
    this.selectorGroup = selectorGroup
    this.groupTag = groupTag
    return this
  }

  protected abstract fun onCreateView(): View

  override fun setSelected(selected: Boolean) {
    val isPreSelected = isSelected
    super.setSelected(selected)
    if (isPreSelected != selected) {
      onSwitchSelected(selected)
    }
  }

  override fun onClick(v: View) {
    if (selectorGroup != null) {
      selectorGroup!!.onSelectorClick(this)
    }
  }

  fun setSelectorTag() {
    selectorTag
  }

  abstract fun onSwitchSelected(isSelect: Boolean)

  companion object {
    const val SINGLE_SELECT = "single"
    const val MULTIPLE_SELECT = "multiple"
  }
}
